package com.ijunfu.threadLocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 *
 * @title  : 解决在线程池中使用ThreadLocal造成内存泄漏的方式：用完即删
 * @author : ijunfu <ijunfu@163.com>
 * @date   : 2023/10/23 18:23
 * @version: 1.0
 * @motto  : 位来可期 - 世界很大，我想看看
 *
 */
public class Main {

    // 启动参数设置：-Xms25m -Xmx25m
    public static void main(String[] args) {
        ThreadLocal<Data> threadLocal = new ThreadLocal<>();

        ExecutorService pool = Executors.newFixedThreadPool(30);

        IntStream.range(0,30).forEach(e -> {

            pool.execute(()->{
                threadLocal.set(new Data());

                // 关键代码：用完即删
                threadLocal.remove();

                try {
                    TimeUnit.SECONDS.sleep(1L);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            });

        });

        pool.shutdown();
    }
}

class Data {
    private int count=0;

    public byte[] buffer = new byte[1024*1024]; // 1MB
}
